package cn.edu.lingnan.service.impl;


import cn.edu.lingnan.domain.Dto.*;
import cn.edu.lingnan.domain.Vo.*;
import cn.edu.lingnan.domain.pojo.*;
import cn.edu.lingnan.mapper.ProjectMapper;
import cn.edu.lingnan.mapper.UserMapper;
import cn.edu.lingnan.service.ProjectService;
import cn.hutool.core.date.DateUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.sql.Timestamp;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

@Service
@Slf4j
public class ProjectServiceImpl implements ProjectService {

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private UserMapper userMapper;

    @Override
    public PageBean list(ProjectDto projectDto) {
        PageHelper.startPage(projectDto.getPageNum(), projectDto.getPageSize());

        Page<Project> page = projectMapper.list( projectDto);

        long total = page.getTotal();
        log.info("total:{}", total);
        List<Project> rows = page.getResult();

        return new PageBean(total, rows);
    }

    @Override
    public ProjectVo findById(Integer id) {

      ProjectVo projectVo =  projectMapper.findProjectById(id);
     Teacher   teacher =   projectMapper.findProjectTeacherById(projectVo.getTeacherId());
     List< User_ProjectVo>  students =  new ArrayList<>();
     //查询负责人信息
        User_ProjectVo leader = userMapper.findUserById(projectVo.getUserId());
     log.info("leader:{}", leader);
     students.add(leader);
     //查询成员信息
        List<Integer> ids= projectMapper.findProjectStudentIds( projectVo.getId());
        for (Integer id1 : ids) {
            User_ProjectVo userVo = userMapper.findUserById(id1);
            students.add( userVo);
        }
        projectVo.setTeacher(teacher);
            projectVo.setUsers(students);
        return  projectVo;
    }

    @Override
    public void deleteMember(Integer projectId, Integer userId) {
        projectMapper.deleteMember(projectId, userId);
    }

    @Override
    public Integer addMember(Integer projectId, Integer userId) {
        //先判断是否已经是负责人
        ProjectVo projectById = projectMapper.findProjectById(projectId);
        //判断项目是否已经停止
        if (projectById.getStatus() == -1) {
            return -1;
        }
        if (projectById.getUserId() == userId) {
            return  0;
        }
        //查询是否是成员，如果没有记录，则添加，有记录且状态是-1，则恢复状态，否则返回"该学生已经在项目中"
        UserProject userProject = userMapper.findUserProject(projectId, userId);
        if (userProject == null) {
            userMapper.addMember(projectId, userId);
        }
        else if ( userProject.getStatus() == -1) {
            userMapper.recoverMember(projectId, userId);
        }
        else {
            return 0;
        }
        return 1;
    }

    @Override
    public void stopProject(Integer projectId,Integer status) {
        projectMapper.stopProject(projectId, status);
    }

    @Override
    @Transactional
    public Integer deleteProject(Integer projectId, Integer userId, String password) {
      String passWord =   userMapper.getPassWord( userId);
      if (!passWord.equals(password)) {
          return 0;
      }
      //先删除成员
        projectMapper.deleteMembers(projectId);
        //删除项目
        projectMapper.deleteProject(projectId);
        return 1;

    }

    @Override
    public void updateProject(UpdateProjectDto updateProjectDto) {
        if (updateProjectDto.getStartTime() != null) {
            updateProjectDto.setStartTime(DateUtil.parse(updateProjectDto.getStartTime()).toString());
        }
        if (updateProjectDto.getEndTime() != null) {
            updateProjectDto.setEndTime(DateUtil.parse(updateProjectDto.getEndTime()).toString());
        }
        projectMapper.updateProject(updateProjectDto);
    }

    @Override
    public void addProject(AddProjectDto addProjectDto) {
        if (addProjectDto.getStartTime() != null) {
            addProjectDto.setStartTime(DateUtil.parse(addProjectDto.getStartTime()).toString());
        }
        if (addProjectDto.getEndTime() != null) {
            addProjectDto.setEndTime(DateUtil.parse(addProjectDto.getEndTime()).toString());
        }
        if(addProjectDto.getType() == 1){
            addProjectDto.setStatus(1);
        }
        else{
            addProjectDto.setStatus(0);
        }
        projectMapper.addProject(addProjectDto);

    }

    @Override
    public void exportExcel(String userName, HttpServletResponse response) throws IOException {
        // 查询数据
        List<Project> projects = projectMapper.selectProjectExcel();
        System.out.println(projects.get(1));

        // 创建工作簿
        Workbook workbook = new XSSFWorkbook();
        Sheet sheet = workbook.createSheet("项目数据");

        // 设置标题和样式
        Row titleRow = sheet.createRow(0);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("项目数据");
        CellStyle titleStyle = createBoldAndCenterCellStyle(workbook);
        titleCell.setCellStyle(titleStyle);
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 8));

        Row userRow = sheet.createRow(1);
        Cell userCell = userRow.createCell(0);
        userCell.setCellValue("用户: " + userName);
        userCell.setCellStyle(createBoldCellStyle(workbook));
        sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, 8));

        Row exportTimeRow = sheet.createRow(2);
        Cell exportTimeCell = exportTimeRow.createCell(0);
        String currentTime = new SimpleDateFormat("yyyy-MM-dd").format(System.currentTimeMillis());
        exportTimeCell.setCellValue("导出时间: " + currentTime);
        exportTimeCell.setCellStyle(createBoldCellStyle(workbook));
        sheet.addMergedRegion(new CellRangeAddress(2, 2, 0, 8));

        Row headerRow = sheet.createRow(3);
        String[] headers = {"项目ID", "负责人", "导师", "项目名称", "状态", "开始时间", "结束时间"};
        CellStyle headerStyle = createBoldAndCenterCellStyle(workbook);
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }

        CellStyle contentStyle = createCenterCellStyle(workbook);
        int rowIndex = 4;
        for (Project record : projects) {
            Row row = sheet.createRow(rowIndex++);
            row.createCell(0).setCellValue(record.getId());
            row.createCell(1).setCellValue(record.getUserName());
            row.createCell(2).setCellValue(record.getTeacherName());
            row.createCell(3).setCellValue(record.getProjectName());
            String status = record.getStatus() == 1 ? "进行中" : "已停止或已结束";
            row.createCell(4).setCellValue(status);
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            row.createCell(5).setCellValue(dateFormat.format(record.getStartTime()));
            row.createCell(6).setCellValue(dateFormat.format(record.getEndTime()));


            for (int i = 0; i <= 6; i++) {
                row.getCell(i).setCellStyle(contentStyle);
            }
        }

        // 自动调整列宽
        for (int i = 0; i < headers.length; i++) {
            sheet.autoSizeColumn(i);
        }

        // 设置响应头
        String fileName = "项目数据.xlsx";
        String encodedFileName = URLEncoder.encode(fileName, StandardCharsets.UTF_8).replaceAll("\\+", "%20");
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition", "attachment; filename*=UTF-8''" + encodedFileName);

        // 将工作簿写入响应流并关闭资源
        try (ServletOutputStream outputStream = response.getOutputStream()) {
            workbook.write(outputStream);
        } finally {
            workbook.close();
        }
    }

    @Override
    public Integer joinProject(Integer projectId, Integer userId) {
        //查询是否是负责人或者项目成员
        Integer count1= projectMapper.findProjectByStudentIdAndProjectId(userId, projectId);
        log.info("count1:{}", count1);
        Integer count2=    projectMapper.findProjectMemberByStudentIdAndProjectId(userId, projectId);
        log.info("count2:{}", count2);
        if(count1>0 || count2>0){
            return  0;
        }
        //判断项目是否已经停止
        ProjectVo projectById = projectMapper.findProjectById(projectId);
        if (projectById.getStatus() == -1) {
            return -1;
        }

        projectMapper.joinProject( userId, projectId);
        return 1;
    }

    @Override
    public List<JoinProjectVo> listJoinProject() {
        List<UserProject> userProjects = projectMapper.findJoinProject();
        List<JoinProjectVo> projectVos = new ArrayList<>();
        for (UserProject userProject : userProjects) {
            JoinProjectVo projectVo = projectMapper.findJoinProjectById(userProject.getProjectId());
            User_ProjectVo userVo = userMapper.findUserById(userProject.getUserId());
            projectVos.add(projectVo);
            projectVo.setUser(userVo);
        }

 return projectVos;
        }

    @Override
    public void agreeJoinProject(Integer projectId, Integer userId) {
        projectMapper.agreeJoinProject(projectId, userId);
    }

    @Override
    public void refuseJoinProject(RejectJoin rejectJoin) {
        projectMapper.refuseJoinProject(rejectJoin);
    }

    @Override
    public List<JoinProjectVo> listMyJoinProject(Integer userId, Integer status) {
      List<UserProject> userVo =   projectMapper.findMyJoinProject(userId, status);
      List<JoinProjectVo> projectVos = new ArrayList<>();
         for ( UserProject userProject : userVo) {
             JoinProjectVo projectVo = projectMapper.findJoinProjectById( userProject.getProjectId());
             if(userProject.getRemark()!=null){
                 projectVo.setRemark(userProject.getRemark());

             }
             projectVos.add(projectVo);
         }
        return  projectVos;
    }

    @Override
    public void cancelApply(Integer userId, Integer projectId) {
        projectMapper.cancelApply(userId, projectId);
    }

    @Override
    public List<Project> listMyProject(Integer userId, Integer status,Integer type) {
        if(type==1 &&  status!=3){
            return  projectMapper.listMyProjectNotType(userId);
        }
        if(status==3){
            return  projectMapper.listMyProjectReject(userId, status);
        }
        return  projectMapper.listMyProject(userId, status);
    }

    @Override
    public void cancelProject(Integer projectId) {
        projectMapper.cancelProject(projectId);
    }

    @Override
    public List<Project> listNeedCheckProject() {
        return  projectMapper.listNeedCheckProject();
    }

    @Override
    public void checkProject(RejectOrAgreeCreate rejectOrAgreeCreate) {
         projectMapper.checkProject(rejectOrAgreeCreate);
    }

    @Override
    public StatisticsVo statistics() {
        StatisticsVo statisticsVo = new StatisticsVo();
        //查询项目总数
        Integer projectCount = projectMapper.countProject();
        statisticsVo.setProjectNum(projectCount);
        //查询用户总数
        Integer userCount = userMapper.countUser();
        statisticsVo.setUserNum(userCount);
        //查询老师总数
        Integer teacherCount = userMapper.countTeacher();
        statisticsVo.setTeacherNum(teacherCount);
        //查询需要审核的项目数
        Integer needCheckProjectCount = projectMapper.countNeedCheckProject();
        statisticsVo.setReviewProject(needCheckProjectCount);
        //查询需要审核的申请数
        Integer needCheckApplyCount = projectMapper.countNeedCheckApply();
        statisticsVo.setReviewApply(needCheckApplyCount);
        //查询前7的项目
        List<Order>  orderList = projectMapper.listProjectBy7();
        statisticsVo.setOrderList(orderList);
         return  statisticsVo;
    }


    // 创建加粗并居中样式的方法
    private CellStyle createBoldAndCenterCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        return style;
    }

    // 创建加粗样式的方法
    private CellStyle createBoldCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        font.setBold(true);
        style.setFont(font);
        return style;
    }

    // 创建居中样式的方法
    private CellStyle createCenterCellStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        return style;
    }

}
